home *** CD-ROM | disk | FTP | other *** search
- Path: swidir.switch.ch!epflnews!Thomas.Wolf
- From: Thomas.Wolf@di.epfl.ch (Thomas Wolf)
- Newsgroups: comp.lang.c
- Subject: Re: returning ptr to struct with ptrs in it?
- Date: 23 Feb 1996 15:51:17 GMT
- Organization: Ecole Polytechnique FΘdΘrale de Lausanne
- Sender: wolf@lglsun5.epfl.ch (Thomas Wolf)
- Message-ID: <4gknpl$3nn@info.epfl.ch>
- References: <4gk852INNbp4@faatcrl.faa.gov>
- NNTP-Posting-Host: lglsun5.epfl.ch
-
- In article <4gk852INNbp4@faatcrl.faa.gov>, lbona@saratoga (lbona) writes:
- [Snip]
- :> When I declare a function that returns a pointer to a struct that contains
- :> pointers, the pointer(s) at the end of the struct get set to garbage after
- :> being returned. Pointers not at the end are not affected.
-
- :> typedef struct bar {
- [Snip]
- :> } BAR;
- :>
- :> BAR *parse_bar(char toke[]);
- :>
- :> main()
- :> {
- :> BAR BB;
- [Snip]
- :> BB = *parse_bar(toke);
- [Snip]
- :> }
-
- :> BAR *parse_bar(char toke[]);
- :> {
- :> BAR bb;
- :>
- :> memset(&bb,0,sizeof(BAR));
- [Snip]
- :> /* read data from file and parse - never touch bb.d, bb.g, or bb.h */
- [Snip]
- :> return(&bb);
- :> }
- [Snip]
-
- In 'parse_bar' you return the address of a local variable. After 'parse_bar'
- has returned, this variable doesn't live anymore! Thus, the pointer you
- returned points to memory which is no longer valid, and of course you'll
- end up with garbage in 'BB' in 'main'. Either return the whole structure,
- not just a pointer to the local 'bb', or - as you said - pass a pointer to
- 'BB' to 'parse_bar'.
-
- Regards,
-
- Thomas
- ----------------------------------------------------------------------
- Swiss Federal Institute of Technology | Thomas Wolf
- Software Engineering Laboratory | EPFL-DI-LGL
- Thomas Wolf (TW) | CH-1015 Lausanne (Suisse)
- E-Mail: wolf@di.epfl.ch | Phone: (++41 21)693 42 37
- ----------------------------------------------------------------------
-
-
-